package io.modelcontextprotocol.autoconfigure.definition;


import cn.pinming.pmsuite.utils.DateUtils;
import cn.pinming.pmsuite.utils.TypeUtils;
import io.modelcontextprotocol.autoconfigure.utils.JsonParser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.lang.Nullable;

import javax.imageio.ImageIO;
import java.awt.image.RenderedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.lang.reflect.Type;
import java.math.BigDecimal;
import java.util.Base64;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public final class DefaultToolCallResultConverter implements ToolCallResultConverter {
    private static final Logger logger = LoggerFactory.getLogger(DefaultToolCallResultConverter.class);

    public DefaultToolCallResultConverter() {
    }

    public String convert(@Nullable Object result, @Nullable Type returnType) {
        if (result==null){
            return "";
        }
        if (returnType == Void.TYPE || returnType == null) {
            logger.debug("The tool has no return type. Converting to conventional response.");
            return JsonParser.toJson("Done");
        } else if (result instanceof String) {
            return (String) result;
        } else if (result instanceof Date) {
            return DateUtils.formatDate((Date) result);
        } else if (returnType instanceof Class && ((Class<?>) returnType).isPrimitive()) {
            return String.valueOf(result);
        } else if (result instanceof RenderedImage) {
            ByteArrayOutputStream buf = new ByteArrayOutputStream(4096);

            try {
                ImageIO.write((RenderedImage)result, "PNG", buf);
            } catch (IOException var5) {
                IOException e = var5;
                return "Failed to convert tool result to a base64 image: " + e.getMessage();
            }

            String imgB64 = Base64.getEncoder().encodeToString(buf.toByteArray());
            Map<String,Object> map=new HashMap<>();
            map.put("mimeType","image/png");
            map.put("data",imgB64);
            return JsonParser.toJson(map);
        } else {
            logger.debug("Converting tool result to JSON.");
            return JsonParser.toJson(result);
        }
    }
}
